#!/usr/bin/python
# -*- coding:utf-8 -*-

from wtforms.fields import DateTimeField, BooleanField, StringField, FieldList
from wtforms.validators import DataRequired

from app.errors import ParameterError
from app.validators import BaseForm
from app.validators.asset import TargetUrl
from app.libs.enums import TASK_TYPE_CONFIG


class ApiTokenForm(BaseForm):

    expired_time = DateTimeField(label="token 过期时间", validators=(DataRequired(),))
    is_active = BooleanField(label="是否启用token")
    is_new_create = BooleanField(label="是否重置token", default=True)
    desc = StringField(label="备注", default="")


class SendMessageConfigForm(BaseForm):

    is_active = BooleanField(default=True, label="是否启用推送")
    url = StringField(label="推送地址", default="")
    auth_type = StringField(label="认证类型", default="")
    add_to = StringField(label="认证参数位置", default="header")
    auth_key = StringField(label="认证参数key", default="")
    auth_value = StringField(label="认证值value", default="")
    method = StringField(label="推送地址访问方式", default="")
    desc = StringField(label="备注", default="")
    task_types = FieldList(StringField())

    def validate_url(self, value):
        if not value.data:
            raise ParameterError(msg='推送地址必填')
        try:
            url = TargetUrl(url=value.data)
        except Exception:
            raise ParameterError(msg='推送地址格式错误')
        return value

    def validate_auth_type(self, value):
        if not value.data:
            raise ParameterError(msg='认证类型必填')
        return value

    def validate_method(self, value):
        if not value.data:
            raise ParameterError(msg='请求方式必填')
        if value.data not in ('POST', 'GET'):
            raise ParameterError(msg='请求方式错误')
        return value

    def validate_task_types(self, task_types):
        task_types = task_types.data
        if set(task_types) - {t for t, c in TASK_TYPE_CONFIG.items() if c["is_allow_api_push"]}:
            raise ParameterError(msg='推送任务类型错误')
        return task_types
